""" Reads in components from list of fort.13 style files, for the LLS
paper. """

import numpy as np
import sys
from astro.io import readcol,writecol
from astro import pyvpfit
from astro.utilities import append_field

SPDLGT = 299792.458    # km/s

def getcomps(inputfilename, VWIDTH=1000.0,centre='mean'):

    filenames = [line.strip() for line in open(inputfilename)]

    absystems = []
    #get each f13 output model
    for name in filenames:
        vpmod = pyvpfit.VpfitModel()
        vpmod.readf13(name)
        absystems.append(vpmod.lines)
    new_absystems = []

    for name,sys in zip(filenames,absystems):
        zref = float(sys.z[0])
        vdelts = np.array([(float(z) - zref) / (1. + zref) * SPDLGT
                           for z in sys.z])
        validlines = sys.compress(np.abs(vdelts) < VWIDTH)
        valid_vdelts = vdelts.compress(np.abs(vdelts) < VWIDTH)
        if centre == 'mean':
            vcent = np.mean(valid_vdelts)
        elif centre == 'median':
            vcent = np.median(valid_vdelts)
            
        print '%s: ' % name 
        print ('mean vel is %s (z=%s), counted %s of %s components' %
               (vcent,zref + vcent/SPDLGT * (1.0+zref),
                len(valid_vdelts),len(vdelts)))
        new_vdelts = np.array([dv - vcent for dv in valid_vdelts])
        new_sys = append_field(validlines,'vdelt',new_vdelts)
        new_sys = append_field(new_sys,'filename',name)
        new_absystems.append(new_sys)

    vdelts = []
    for sys in new_absystems:
        vdelts.extend(sys['vdelt'])

    return new_absystems,vdelts

